import { customRef, getCurrentInstance, onBeforeUnmount } from 'vue'

export interface DelayLoadingOption {
  /**
   * 延时时间（单位：ms）
   * @default 100
   */
  delay?: number
  /**
   * 初始值
   * @default false
   */
  initialValue?: boolean
}

export function useDelayLoading(option: DelayLoadingOption = {}) {
  const { initialValue = false, delay = 100 } = option

  let _value = initialValue
  let _timer = 0

  function clearTimer() {
    if (!_timer) return

    clearTimeout(_timer)
    _timer = 0
  }

  if (getCurrentInstance()) {
    onBeforeUnmount(clearTimer)
  }

  return customRef((track, trigger) => {
    return {
      get() {
        track()
        return _value
      },
      set(value) {
        if (value) {
          if (_timer || _value) return

          _timer = setTimeout(() => {
            _timer = 0
            _value = value
            trigger()
          }, delay)
        } else {
          if (_value) {
            _value = value
            trigger()
          } else {
            clearTimer()
          }
        }
      }
    }
  })
}
